/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.tdc.visitor.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.zxing.BarcodeFormat;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.QRCode;
import com.thinkgem.jeesite.modules.tdc.department.entity.TdcDepartment;
import com.thinkgem.jeesite.modules.tdc.times.entity.TdcTimes;
import com.thinkgem.jeesite.modules.tdc.visitor.dao.TdcVisitorReservationDao;
import com.thinkgem.jeesite.modules.tdc.visitor.entity.TdcVisitorReservation;
import com.thinkgem.jeesite.modules.tdc.visitor.entity.TdcVisitorReservationJson;

/**
 * 前台首页-预约Service
 * @author 曹红
 * @version 2017-03-21
 */
@Service(value="tdcVisitorService")
@Transactional(readOnly = true)
public class TdcVisitorReservationService extends CrudService<TdcVisitorReservationDao, TdcVisitorReservation> {
	
	@Autowired
	private TdcVisitorReservationDao tdcVisitorReservationDao;
	
	private static Calendar calendar = new GregorianCalendar();
	
	public TdcVisitorReservation get(String id) {
		return super.get(id);
	}
	
	/**
	 * 获得部门信息
	 * @return 部门信息的集合
	 */
	public List<TdcDepartment> getDepts(){
		return tdcVisitorReservationDao.getDepts();
	}
	
	/**
	 * 获得预约时间信息
	 * @return 包含预约时间信息的集合
	 */
	public List<TdcTimes> getTimes(){
		return tdcVisitorReservationDao.getTimes();
	}
	/**
	 * 验证--预约开始、结束时间段
	 * @param bespeakStart	预约开始时间
	 * @param bespeakEnd	预约结束时间
	 * @param bespeakType	预约类型（提审提讯、会见）
	 * @return 判断状态 1~7
	 */
	public int checkTime(String bespeakStart,String bespeakEnd,String bespeakType){
		try{
			String[]datetime = bespeakStart.split(" ");
			String[]date = datetime[0].split("-");		
			String[]time = datetime[1].split(":");
			int yyyy = Integer.parseInt(date[0]);
			int MM = Integer.parseInt(date[1]);
			int dd = Integer.parseInt(date[2]);
			int hh = Integer.parseInt(time[0]);
			int mm = Integer.parseInt(time[1]);
			time = (bespeakEnd.split(" "))[1].split(":");
			int hh1 = Integer.parseInt(time[0]);
			int mm2 = Integer.parseInt(time[1]);
			/*转换为分钟，好算*/
			/*预约人的预约开始时间*/
			int tmpStartEndDays = yyyy*365 + MM*30 + dd; 
			int tmphhmm1 = hh*60+mm;
			/*预约人的预约结束时间*/
			int tmphhmm2 = hh1*60+mm2;
			if((tmphhmm2 - tmphhmm1) < 5){
				/*预约时间太短*/
				return 7;
			}
			
			Calendar cal=Calendar.getInstance();
			cal.set(yyyy - 1900,MM,dd);
			
			int iweek = cal.get(Calendar.DAY_OF_WEEK); 
			String sweek;
			switch(iweek){
				case 1:sweek="星期天";break;
				case 2:sweek="星期一";break;
				case 3:sweek="星期二";break;
				case 4:sweek="星期三";break;
				case 5:sweek="星期四";break;
				case 6:sweek="星期五";break;
				case 7:sweek="星期六";break;
				default:sweek="星期六";
			}
			
			int ampmtotals = 0;
			TdcTimes theWeekTimes = tdcVisitorReservationDao.getWeek(sweek);
			
			/*是否小于当前时间，提前一个小时预约*/
			cal.setTime(new Date());
			
			int tmphhmm = cal.get(Calendar.HOUR_OF_DAY)*60 + cal.get(Calendar.MINUTE) + 60;
			int tmpDays = cal.get(Calendar.YEAR)*365 + cal.get(Calendar.MONTH)*30 + cal.get(Calendar.DAY_OF_MONTH);
			System.out.println(tmpStartEndDays+"--"+tmphhmm1+"\n"+tmpDays+"--"+tmphhmm);
			if((tmpStartEndDays <= tmpDays)&&(tmphhmm1 < tmphhmm)){
				/*预约开始时间早于当前时间 + 60分钟*/
				return 8;
			}
			
			/*是否小于预约开始时间*/
			String[] bstmp = theWeekTimes.getBespeakStart().split(":");
			tmphhmm = Integer.parseInt(bstmp[0])*60 + Integer.parseInt(bstmp[1]);
			if(tmphhmm1 < tmphhmm){
				/*预约开始时间小于当天的预约开始时间*/
				return 5;
			}
			
			/*是否大于预约结束时间*/
			bstmp = theWeekTimes.getBespeakEnd().split(":");
			tmphhmm = Integer.parseInt(bstmp[0])*60 + Integer.parseInt(bstmp[1]) + Integer.parseInt(theWeekTimes.getBespeakDelay());
			System.out.println(tmpStartEndDays+"--"+tmphhmm2+"\n"+tmpDays+"--"+tmphhmm);
			if((tmpStartEndDays >= tmpDays)&&(tmphhmm2 > tmphhmm)){
				/*预约结束时间大于当天的预约结束时间（+预约延迟时间）*/
				return 6;
			}
			
			if(hh < 12)ampmtotals = Integer.parseInt(theWeekTimes.getAmQuantity());
			else ampmtotals = Integer.parseInt(theWeekTimes.getPmQuantity());
			
			/*指定预约时间段、指定预约类型的预约人数*/
			int num = tdcVisitorReservationDao.startEndNum(bespeakStart,bespeakEnd,bespeakType);
			/*预约那天上午（或下午）的预约量已满*/
			if(num >= ampmtotals)return 3;
			/*指定预约类型（提审 或 会见）的房间数*/
			int rooms = tdcVisitorReservationDao.typeRooms(bespeakType);
			/*若指定时间段的预约人数 >= 该时间段该预约类型的房间数，则返回2*/
			/*指定时间段该预约类型的房间已满--预约人数已满*/
			if(num >= rooms)return 2;
			
			/*可以预约*/
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			/*系统错误*/
			return 4;
		}
	}
	/**
	 * 
	 * todayCount:(当天预约总量)
	 * 
	 * @return
	 */
	
	public int todayCount(){
		return tdcVisitorReservationDao.todayCount();
	}
	/**
	 * 
	 * arrivedCount:(当天已到数量)
	 * 
	 * @return
	 */
	
	public int arrivedCount(){
		return tdcVisitorReservationDao.arrivedCount();
	}
	
	/**
	 * 生成二维码图片,并保存在src/main/webapp/static/inages2code文件夹里,
	 * 返回该二维码图片的路径
	 * @param path 该二维码存的路径 ，以"/"结束
	 * @return 该二维码图片的名字
	 */
	public String get2Code(String path,String bsnumber){
		QRCode qrc = new QRCode();
		String filePostfix="png";
		/*没有父目录，创建*/
		File parentfile = new File(path);
		if(!parentfile.exists()){
			parentfile.mkdirs();
		}
		File file = new File(path + "/" + bsnumber + "."+filePostfix);
		if(!file.exists())file.mkdirs();
		/*生成QRCode二维码*/
		qrc.encode(bsnumber, file,filePostfix, BarcodeFormat.QR_CODE, 5000, 5000, null);
		/*解析QRCode二维码*/
//		qrc.decode(file);
		return bsnumber + ".png";
	}
	/**
	 * 自动生成预约编号
	 * 获取预约编号
	 * @return 预约编号
	 */
	public String getBNumber() {
		/*获取当前系统时间的年月日*/
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String yyyymmdd = format.format(Calendar.getInstance().getTime());
		/*获取当前数据库中预约信息表里的最大的预约编号*/
		String bn01 = tdcVisitorReservationDao.getMaxBespeakNumber();
		/*说明当前数据库无数据*/
		if(null == bn01 || "".equals(bn01))return yyyymmdd + "001";
		/*取时间*/
		String bnymd = bn01.substring(0,8);
		/*取编号（001~999）*/
		String bnnum = bn01.substring(8,bn01.length());
		/*要获取的编号*/
		String bnumber;
		
		if(!yyyymmdd.equals(bnymd) || null == bnymd || "".equals(bnymd)){//说明已经过了一天，或者数据库中没有值
			bnumber = yyyymmdd + "001";
			System.out.println(1111);
		}else{
			int number = Integer.parseInt(bnnum) + 1;
			if(number<10){
				bnnum="00"+number;
			}else if(number>=10 && number<100){
				bnnum="0"+number;
			}else if(number>=100 && number<1000){
				bnnum=""+number;
			}else bnnum = "";/*超过999，获取的预约编号不对（当天的预约人数太太太多），后缀为"",后面根据获取的预约编号的长度（==11，正确，==8，不对）判断该预约编号是否正确。*/
			bnumber = yyyymmdd+bnnum;
		}
		return bnumber;
	}
	/**
	 * 根据 预约编号查询相关的预约信息
	 * @param bespeakNumber 预约编号
	 */
	public TdcVisitorReservationJson getByBespeakNumber(String bespeakNumber){
		return tdcVisitorReservationDao.getByBespeakNumber(bespeakNumber); 
	}
	
	public List<TdcVisitorReservation> findList(TdcVisitorReservation TdcVisitorReservation) {
		return super.findList(TdcVisitorReservation);
	}
	
	public Page<TdcVisitorReservation> findPage(Page<TdcVisitorReservation> page, TdcVisitorReservation TdcVisitorReservation) {
		return super.findPage(page, TdcVisitorReservation);
	}
	/**
	 * 保存对象
	 * @param tdcVisitorReservation 保存对象
	 * @param path 保存二维码的绝对路径 形如:"D:/........../userfiles/1/images/images2code/2002/01/"
	 * @param pathyyyymm 保存二维码的相对路径--存入数据库，形如 "/userfiles/1/images/images2code/2002/01/"
	 * @param ctx 项目名，形如 "/tdc"
	 * @return 保存的对象
	 */
	@Transactional(readOnly = false)
	public TdcVisitorReservation save(TdcVisitorReservation tdcVisitorReservation,String path,String pathyyyymm,String ctx) {
		String bnumber = getBNumber();
		
		if(bnumber.length() < 11){
			return null;
		}else{
			tdcVisitorReservation.setBespeakNumber(bnumber);
			tdcVisitorReservation.setBespeakStatus("未到");
			/*生成该预约对象指定的二维码，返回二维码 图片名*/
			String path2code = get2Code(path, bnumber);
			tdcVisitorReservation.setBespeak2code(ctx + pathyyyymm + path2code);
			super.save(tdcVisitorReservation);
			return tdcVisitorReservation;
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(TdcVisitorReservation TdcVisitorReservation) {
		super.delete(TdcVisitorReservation);
	}
	
	/**
	 *获得当前时间的年月，形如"2002/03/"
	 * @return 形如"2002/03/" 的字符串
	 */
	public static String yyyymm(){
		int month = (calendar.get(Calendar.MONTH) + 1);
		String smonth;
		if(month < 10)smonth = "0" + month;
		else smonth = "" + month;
/*		指定目录+年+月*/
		return calendar.get(Calendar.YEAR) + "/" + smonth + "/";
	}
	
}